import nprogress from 'nprogress';
import type { Router } from 'vue-router';

import usePermission from '@/hooks/permission';
import { useUserStore, useAppStore } from '@/store';
import { addServerRoutes } from '@/utils/router-helper';

import { NOT_FOUND_NAME, NOT_FOUND } from '../constants';
import { appRoutes } from '../routes';

let isFirst = true;
let isServerRoutesAdd = false;

export default function setupPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (to.name === 'login') {
      next();
      nprogress.done();
      return;
    }
    const appStore = useAppStore();
    const userStore = useUserStore();
    const permission = usePermission();
    appStore.loadStart();
    if (appStore.menuFromServer) {
      // 如果服务器菜单未加载，则需要等待服务器菜单加载完毕
      if (!appStore.appAsyncMenus.length) {
        await appStore.fetchServerMenu();
      }
      // 如果动态路由未添加，并且服务器菜单已加载，则添加动态路由
      if (!isServerRoutesAdd && appStore.appAsyncMenus.length) {
        addServerRoutes(router);
        isServerRoutesAdd = true;
      }
      if (to.name !== NOT_FOUND_NAME) {
        // 如果路由名称不是NOT_FOUND，说明路由已经匹配到，则继续访问
        next();
      } else if (isFirst) {
        isFirst = false;
        next(to.fullPath);
      } else {
        next();
      }
    } else {
      if (permission.accessRouter(to)) {
        next();
      } else {
        const destination =
          permission.findFirstPermissionRoute(appRoutes, userStore.role) ||
          NOT_FOUND;
        next(destination);
      }
    }
  });
  router.afterEach(() => {
    const appStore = useAppStore();
    appStore.loadDone();
    nprogress.done();
  });
}
